package v1

import (
	"fmt"
	"image"
	"image/color"
	"image/png"
	"os"
	"saas-app/app/dao"
	"saas-app/app/define"
	"saas-app/app/model"
	"saas-app/app/service"
	"saas-app/library/response"

	"github.com/gogf/gf/crypto/gmd5"
	"github.com/gogf/gf/util/gconv"

	"github.com/gogf/gf/net/ghttp"
)

const (
	dx = 256
	dy = 256
)

func Pic(dx, dy int) [][]uint8 {
	pic := make([][]uint8, dx)
	for i := range pic {
		pic[i] = make([]uint8, dy)
		for j := range pic[i] {
			pic[i][j] = uint8(i * j % 255)
		}
	}
	return pic
}

func Draw(r *ghttp.Request) {
	file, err := os.Create("test.png")
	if err != nil {
		fmt.Println(err)
	}
	defer file.Close()
	rgba := image.NewRGBA(image.Rect(0, 0, dx, dy))
	for x := 0; x < dx; x++ {
		for y := 0; y < dy; y++ {
			rgba.Set(x, y, color.RGBA{uint8(x * y % 255), uint8(x * y % 255), 0, 255})
		}
	}
	err = png.Encode(file, rgba)
	if err != nil {
		fmt.Println(err)
	}

	r.Response.Write(file)
}

// 登录
func Login(r *ghttp.Request) {
	passport := r.GetFormString("passport")
	password := r.GetFormString("password")

	result := service.UserService().Login(passport, password)

	response.JsonExit(r, 0, "ok", result)
}

// 注册
func SignUp(r *ghttp.Request) {
	var (
		data        *define.SignUpRequest
		signUpParam *define.SignUpParam
	)
	if err := r.Parse(&data); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	if err := gconv.Struct(data, &signUpParam); err != nil {
		response.JsonExit(r, 1, err.Error())
	}
	result := service.UserService().SignUp(signUpParam)
	response.JsonExit(r, 0, "ok", result)
}

// 用户详情
func UserInfo(r *ghttp.Request) {

	id := r.GetQueryUint("id")

	if id == 0 {
		id = r.GetCtxVar("user_id").Uint()
	}

	result := service.UserService().GetUserInfoById(id)
	response.JsonExit(r, 0, "ok", result)
}

// 修改用户信息
func UpdateUserInfo(r *ghttp.Request) {

	var reqMap = make(map[string]interface{})
	id := r.GetFormUint("id")

	if r.GetForm("nickname") != nil {
		reqMap["nickname"] = r.GetFormString("nickname")
	}

	if r.GetForm("password") != nil {
		reqMap["password"] = r.GetFormString("password")
	}
	reqMap["password"] = gmd5.MustEncrypt(reqMap["password"])
	if err := service.UserService().UserUpdate(id, reqMap); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "ok", "修改成功")
	}
}

// 退出
func Signout(r *ghttp.Request) {
	userid := r.GetCtxVar("user_id").Uint()
	if err := service.UserService().Signout(userid); err != nil {
		response.JsonExit(r, 1, err.Error())
	} else {
		response.JsonExit(r, 0, "ok", nil)
	}
	response.JsonExit(r, 0, "ok", nil)
}

type UserR struct {
	Id uint `orm:"id,primary"      json:"id"` //
	*model.User
	SchoolUser []*model.SchoolUser `orm:"with:user_id=id"`
	UserToken  []*model.UserToken  `orm:"with:user_id=id"`
}

func Test(r *ghttp.Request) {
	var user UserR
	dao.User.WithAll().Scan(&user)
	response.JsonExit(r, 0, "ok", user)
}
